﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration.Assemblies;
using System.Data;
using System.Data.SqlClient;
using System.Web.SessionState;
using FaithCMS;
using Microsoft.Data.Odbc;
using System.Drawing;

namespace FaithCMSControls
{
    [Serializable]
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:TargetedLogin runat=server></{0}:TargetedLogin>")]
    public partial class TargetedLogin : CompositeControl, INamingContainer
    {
        //Private variable to store the connection string for the database
        private string connString;

        //Member controls
        [NonSerialized]
        protected static TextBox textBoxUserName = new TextBox();

        [NonSerialized]
        protected static TextBox textBoxPassword = new TextBox();

        [NonSerialized]
        protected Label lblUserName;

        [NonSerialized]
        protected Label lblPassword;

        [NonSerialized]
        protected DropDownList destList;

        [NonSerialized]
        protected CheckBox rememberPassword;

        [NonSerialized]
        protected HyperLink forgotPassLink;

        [NonSerialized]
        protected Button submitButton;

        //Private variable to hold the current destination
        private static string destination;

        //Delegate to handle the event
        public delegate void AuthenticatedHandler(object o, EventArgs e);

        //Event declaration for User Authentication
        public event AuthenticatedHandler UserAuthenticated;

        //Destination Dictionary
        Dictionary<string, string> dictionaryDestinations;

        //List of target locations
        List<string> targetLocations;

        //Default constructor
        public TargetedLogin()
            : base()
        {
            
        }

        //Text Property
        public string Text
        {
            get
            {
                return "Not Implemented";
            }

            set
            {
                try
                {
                    throw new NotImplementedException("This text property isn't being used. Child Control properties are being used instead to prevent ViewState clutter.");
                }
                catch (NotImplementedException nException)
                {
                    Console.WriteLine(nException.Message);
                }
            }
        }

        //Username Text Property
        public static string UserText
        {
            get
            {
                return textBoxUserName.Text;
            }

            set
            {
                textBoxUserName.Text = value;
            }
        }

        //Password Text Property
        public static string PasswordText
        {
            get
            {
                return textBoxPassword.Text;
            }

            set
            {
                textBoxPassword.Text = value;
            }
        }
        
        public static string Destination
        {
            get
            {
                //Return the destList dropdown list selected value
                return destination;
            }

            set
            {
                //Set the destList value
                destination = value;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        /// <summary>
        /// UserAuthenticated EventHandler
        /// </summary>
        /// <param name="o">Object that triggered the event</param>
        /// <param name="e">Event arguments</param>
        public void OnAuthenticated(object o, EventArgs e)
        {
            //Set the connection string
            connString = WebConfiguration.ConnectionString;

            //Initialize the data set
            DataSet ds = new DataSet("users");

            //Initialize the connection
            OdbcConnection conn = new OdbcConnection(connString);

            //Initialize the command object
            OdbcCommand comm = new OdbcCommand("CALL CheckUsers(?,?)", conn);
            comm.CommandType = CommandType.StoredProcedure;
            comm.Parameters.Add("user", UserText);
            comm.Parameters.Add("pass", PasswordText);

            //Initialize the data adapter with the command object
            OdbcDataAdapter ODBCDataAdapter = new OdbcDataAdapter(comm);

            //Fill the data set and set the source table
            ODBCDataAdapter.Fill(ds, "users");

            //If the user exists
            if (ds.Tables["users"].Rows.Count != 0)
            {
                foreach (DataRow r in ds.Tables["users"].Rows)
                {
                    if (string.IsNullOrEmpty(SessionManager.UserID) && string.IsNullOrEmpty(SessionManager.UserRole))
                    {
                        //Store the user data in the Session Manager
                        SessionManager.UserID = r["user"].ToString();
                        SessionManager.UserRole = ds.Tables["users"].Rows[0]["role"].ToString();

                        //Set SessionManager Authenticated Property to true
                        SessionManager.Authenticated = true;
                    }
                }
                //Trigger the Authentication Event (Note: Ensure that this fires only if the user is valid)
                UserAuthenticated(o, e);
            }
            else
            {
                //The user is not valid
                this.Controls.Add(new LiteralControl("<p style=\"font-size: 14px; color: red;\">Invalid User</p>"));
            }

            //Close the connection
            conn.Close();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            lblUserName = new Label();
            lblUserName.Text = "Username: ";

            this.Controls.Add(lblUserName);

            this.Controls.Add(textBoxUserName);

            Controls.Add(new LiteralControl("<br/>"));

            lblPassword = new Label();
            lblPassword.Text = "Password: ";

            this.Controls.Add(lblPassword);

            textBoxPassword.CssClass = "passwordTextbox";
            textBoxPassword.TextMode = TextBoxMode.Password;

            this.Controls.Add(textBoxPassword);

            Controls.Add(new LiteralControl("<br/><br/>"));

            destList = new DropDownList();
            destList.CssClass = "destinationSelection";
            destList.Items.Add(new ListItem("Admin Dashboard"));
            destList.Items.Add(new ListItem("Add News"));
            destList.Items.Add(new ListItem("Add Photos"));
            destList.Items.Add(new ListItem("Add Audio"));
            destList.Items.Add(new ListItem("Add Video"));
            destList.Items.Add(new ListItem("Account Settings"));
            destList.Items.Add(new ListItem("Calendar Settings"));
            destList.SelectedIndexChanged += new EventHandler(OnIndexChanged);

            this.Controls.Add(destList);

            Controls.Add(new LiteralControl("<br/><br/>"));

            submitButton = new Button();
            submitButton.CssClass = "submitButton";
            submitButton.Text = "Login";
            submitButton.Click += new EventHandler(OnAuthenticated);

            this.Controls.Add(submitButton);

            Controls.Add(new LiteralControl("<br/><br/>"));

            rememberPassword = new CheckBox();
            rememberPassword.ID = "rememberPassword";
            rememberPassword.CssClass = "rememberPass";
            rememberPassword.Text = "Remember Password?&nbsp;&nbsp;&nbsp;";
            rememberPassword.TextAlign = TextAlign.Left;
            rememberPassword.ForeColor = Color.Blue;
            rememberPassword.CheckedChanged += new EventHandler(rememberPassword_CheckedChanged);

            this.Controls.Add(rememberPassword);

            dictionaryDestinations = new Dictionary<string, string>();

            targetLocations = new List<string>();

            //Add the locations (must be in the same order as the destList values)
            targetLocations.Add(@"/Admin/AdminPage.aspx");
            targetLocations.Add(@"/Admin/AdminNews.aspx");
            targetLocations.Add(@"/Admin/AdminImages.aspx");
            targetLocations.Add(@"/Admin/AdminAudio.aspx");
            targetLocations.Add(@"/Admin/AdminVideo.aspx");
            targetLocations.Add(@"/Admin/Accounts.aspx");
            targetLocations.Add(@"/Admin/Calendar.aspx");

            for (int i = 0; i < destList.Items.Count; i++)
            {
                //Add the key, value pair for the current destination to the dictionary
                dictionaryDestinations.Add(destList.Items[i].Text, targetLocations[i]);
            }

            //Default to main admin page (gets the value associated with the dictionary key and sets it as the destination)
            Destination = dictionaryDestinations["Admin Dashboard"];

            this.ChildControlsCreated = true;
        }

        /// <summary>
        /// Used to store the user's password if they have been authenticated
        /// </summary>
        /// <param name="sender">Calling object</param>
        /// <param name="e">EventArgs parameter</param>
        protected void rememberPassword_CheckedChanged(object sender, EventArgs e)
        {
            //If the checkbox is checked
            if (rememberPassword.Checked)
            {
                //If the browser supports cookies
                if (HttpContext.Current.Request.Browser.Cookies)
                {
                    //If the login session cookie exists
                    if (HttpContext.Current.Request.Cookies["FAITHCMS_LOGIN"] != null)
                    {
                        //Retrieve the password value
                        PasswordText = HttpContext.Current.Request.Cookies["FAITHCMS_LOGIN"].Values["Password"];
                    }
                    else
                    {
                        //Create the cookie with an expiration value of 1 day
                        HttpContext.Current.Response.Cookies["FAITHCMS_LOGIN"].Expires = DateTime.Now.AddDays(1);

                        //Write the username and password to the cookie
                        HttpContext.Current.Response.Cookies["FAITHCMS_LOGIN"].Values["Username"] = UserText;
                        HttpContext.Current.Response.Cookies["FAITHCMS_LOGIN"].Values["Password"] = PasswordText;
                    }
                }
            }
        }

        private void OnIndexChanged(object sender, EventArgs e)
        {
            //Get the target location
            string targetLocation = destList.SelectedValue;

            //Set the destination
            Destination = dictionaryDestinations[targetLocation];
        }
    }
}
